<template>
  <div class="active-list-item relative" @click.stop="activeConfig">
    <div class="top">
      <div class="image">
        <img alt="" src="https://qushen-file.oss-cn-beijing.aliyuncs.com/outsourcing-2023/zhi-hui/admin/cover.jpeg" />
        <div class="meeting-status" :class="getStatusClass(currentState(item))">
          {{ currentState(item) }}
        </div>
        <div class="meeting-open-status" :class="item.isOpen ? 'open' : 'closed'">
          {{ item.isOpen ? '开放中' : '已关闭' }}
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="title">
        <div class="span_title">
          {{ item.title }}
        </div>

        <span class="edit-icon" @click.stop="handleEdit(item)">
          <el-icon color="#61b3f6" size="16">
            <edit />
          </el-icon>
        </span>
      </div>

      <div class="meeting-info">
        <div class="info-row">
          <i class="el-icon-time info-icon">
            <el-icon><calendar /></el-icon>
          </i>
          <span class="info-text">{{ formatDate(item.startTime) }}</span>
        </div>
        <div class="info-row">
          <i class="el-icon-time info-icon">
            <el-icon><clock /></el-icon>
          </i>
          <span class="info-text">{{ formatTime(item.startTime) }} - {{ formatTime(item.endTime) }}</span>
        </div>
        <div class="info-row">
          <i class="el-icon-location info-icon">
            <el-icon><location /></el-icon>
          </i>
          <span
            v-if="item.conferenceRoomManagementInfo?.positionDescription || item.conferenceRoomManagementInfo?.roomName"
            class="info-text location"
          >
            {{ `${item.conferenceRoomManagementInfo?.positionDescription}${item.conferenceRoomManagementInfo?.roomName}会议室` }}
          </span>
          <span v-else class="info-text location">暂无详细地址</span>
        </div>
      </div>

      <div class="config">
        <el-tooltip content="会议配置" placement="top">
          <div class="action-btn" @click.stop="activeConfig">
            <el-icon color="#61b3f6" size="16"><setting /></el-icon>
            <span class="text-base">配置</span>
          </div>
        </el-tooltip>

        <el-tooltip :content="item.isOpen ? '关闭会议' : '开放会议'" placement="top">
          <div class="action-btn" @click.stop="toggleOpenStatus">
            <el-icon :color="item.isOpen ? '#67C23A' : '#909399'" size="16">
              <template v-if="item.isOpen">
                <unlock />
              </template>
              <template v-else>
                <lock />
              </template>
            </el-icon>
            <span class="text-base" :style="{ color: item.isOpen ? '#67C23A' : '#909399' }">
              {{ item.isOpen ? '开放' : '关闭' }}
            </span>
          </div>
        </el-tooltip>

        <el-tooltip content="会议签到" placement="top">
          <div class="action-btn" @click.stop="goToPage('SignInPage', item)">
            <el-icon color="#61b3f6" size="16"><check /></el-icon>
            <span class="text-base">签到</span>
          </div>
        </el-tooltip>

        <el-tooltip content="签到二维码" placement="top">
          <div class="action-btn" @click.stop="showQRCode">
            <el-icon color="#409EFF" size="16"><picture-rounded /></el-icon>
            <span class="text-base">签到码</span>
          </div>
        </el-tooltip>

        <el-tooltip v-if="item.id != '8v0261B7W3ioHoEd'" content="删除会议" placement="top">
          <div class="action-btn delete" @click.stop="handleDelete(item.id)">
            <el-icon color="#fd5058" size="16"><delete /></el-icon>
            <span class="text-base">删除</span>
          </div>
        </el-tooltip>
      </div>
    </div>
  </div>

  <!-- 添加二维码弹窗 -->
  <el-dialog v-model="qrCodeDialogVisible" align-center class="qrcode-dialog" title="签到二维码" width="350px">
    <div class="qrcode-container">
      <div class="qrcode-title">{{ item.title }}</div>
      <div ref="qrcodeRef" class="qrcode-wrapper">
        <qrcode-vue level="H" :size="200" :value="qrCodeValue" />
      </div>
      <div class="qrcode-tips">扫描二维码进行会议签到</div>
    </div>
    <div class="qrcode-actions">
      <el-button type="primary" @click="downloadQRCode">下载二维码</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { Calendar, Check, Clock, Delete, Edit, Location, Lock, PictureRounded, Setting, Unlock } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { ElDialog, ElMessage } from 'element-plus'
import html2canvas from 'html2canvas'
import QrcodeVue from 'qrcode.vue'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { Meeting } from '../config'

const router = useRouter()

const props = defineProps<{
  item: Meeting
}>()

const emits = defineEmits(['handleDelete', 'activeConfig', 'activeEdit', 'toggleOpenStatus'])

const activeConfig = () => {
  emits('activeConfig', props.item.id, props.item.signUpType, props.item.title)
}

const currentDate = dayjs()

// 二维码相关
const qrCodeDialogVisible = ref(false)
const qrcodeRef = ref(null)

// 生成带有活动ID
const qrCodeValue = computed(() => {
  return props.item.id
})

// 显示二维码弹窗
const showQRCode = () => {
  qrCodeDialogVisible.value = true
}

// 下载二维码图片
const downloadQRCode = async () => {
  try {
    if (!qrcodeRef.value) return

    const canvas = await html2canvas(qrcodeRef.value)
    const dataUrl = canvas.toDataURL('image/png')

    // 创建一个下载链接
    const link = document.createElement('a')
    link.download = `签到码_${props.item.title}.png`
    link.href = dataUrl
    link.click()

    ElMessage.success('二维码下载成功')
  } catch (error) {
    console.error('下载二维码失败:', error)
    ElMessage.error('下载二维码失败')
  }
}

const copyToClipboard = (text: string) => {
  if (navigator.clipboard && window.isSecureContext) {
    // 对于支持 Clipboard API 的现代浏览器
    navigator.clipboard
      .writeText(text)
      .then(() => {
        ElMessage.success('签到页面地址已复制到剪贴板')
      })
      .catch(() => {
        fallbackCopyToClipboard(text)
      })
  } else {
    // 后备方案
    fallbackCopyToClipboard(text)
  }
}

const fallbackCopyToClipboard = (text: string) => {
  try {
    const textArea = document.createElement('textarea')
    textArea.value = text
    textArea.style.position = 'fixed'
    textArea.style.left = '-9999px'
    textArea.style.top = '0'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    try {
      document.execCommand('copy')
      ElMessage.success('签到页面地址已复制到剪贴板')
    } catch (error) {
      ElMessage.error('复制失败，请手动复制')
      console.error('复制失败:', error)
    }

    document.body.removeChild(textArea)
  } catch (error) {
    ElMessage.error('复制失败，请手动复制')
    console.error('复制失败:', error)
  }
}

const goToPage = (name: string) => {
  if (name === 'SignInPage') {
    const signInUrl = `${window.location.origin}/#/signIn/signInPage?activeId=${props.item.id}&name=${encodeURIComponent(props.item.title)}`
    copyToClipboard(signInUrl)
    router.push({
      name,
      query: { activeId: props.item.id, name: props.item.title },
    })
  } else {
    router.push({ name })
  }
}

const handleEdit = (params: any) => {
  console.log({ ...params })
  emits('activeEdit', { ...params })
}
const handleDelete = async (id: string) => {
  emits('handleDelete', id)
}

const currentState = computed(() => {
  return (item: any) => {
    if (currentDate.isBefore(item.startTime)) {
      return '未开始'
    } else if (currentDate.isAfter(item.endTime)) {
      return '已结束'
    } else {
      return '进行中'
    }
  }
})

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  return dayjs(dateString).format('YYYY年MM月DD日')
}

// 格式化时间显示
const formatTime = (dateString) => {
  if (!dateString) return '未设置'
  return dayjs(dateString).format('HH:mm')
}

// 获取状态对应的类名
const getStatusClass = (status) => {
  switch (status) {
    case '未开始': {
      return 'status-pending'
    }
    case '已结束': {
      return 'status-ended'
    }
    case '进行中': {
      return 'status-active'
    }
    default: {
      return 'status-pending'
    }
  }
}

// 切换会议开放状态
const toggleOpenStatus = (event: Event) => {
  event.stopPropagation()
  // 触发父组件的toggleOpenStatus事件，传递当前会议ID和反转后的开放状态
  emits('toggleOpenStatus', {
    id: props.item.id,
    isOpen: !(props.item.isOpen ?? true), // 如果isOpen属性不存在，默认为true
  })
}

// 注释掉未使用的函数
// const goToScreen = (id: string | number) => {
//   router.push({
//     name: 'DataScreen',
//     query: { activityId: id },
//   })
// }
</script>

<style lang="scss" scoped>
.InvitationCode {
  display: flex;
  margin-left: 5px;
}
.title1 {
  background: #f1e2c9;
}
.config {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}

.text-base {
  margin-left: 5px;
  font-size: 12px;
  font-weight: 500;
}

.active-list-item:active {
  display: block;
}

.active-list-item {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 340px;
  overflow: hidden;
  cursor: pointer;
  background-color: #f9fcff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
    transform: translateY(-5px);
  }

  .top {
    position: relative;
    flex: none;

    .image {
      position: relative;
      width: 100%;
      height: 150px;
      overflow: hidden;
      font-size: 0;
      pointer-events: none;
      user-select: none;
      border-radius: 10px 10px 0 0;
      -webkit-user-drag: none;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .meeting-status {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1;
        padding: 4px 10px;
        font-size: 12px;
        font-weight: 500;
        color: white;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
      }

      .meeting-open-status {
        position: absolute;
        top: 10px;
        left: 10px;
        z-index: 1;
        padding: 4px 10px;
        font-size: 12px;
        font-weight: 500;
        color: white;
        border-radius: 4px;

        &.open {
          background-color: rgba(64, 158, 255, 0.9);
        }

        &.closed {
          background-color: rgba(144, 147, 153, 0.9);
        }
      }
      ß .status-pending {
        background-color: rgba(230, 162, 60, 0.9);
      }

      .status-active {
        background-color: rgba(103, 194, 58, 0.9);
      }

      .status-ended {
        background-color: rgba(144, 147, 153, 0.9);
      }
    }
  }

  .bottom {
    display: flex;
    flex: 1;
    flex-direction: column;
    padding: 16px;
    background: #f9fcff;
    border-radius: 5px;

    .title {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 600;

      .span_title {
        display: -webkit-box;
        width: 90%;
        min-height: 2.4em;
        overflow: hidden;
        color: #303133;
        text-overflow: ellipsis;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }

      .edit-icon {
        padding: 4px;
        margin-top: 2px;
        border-radius: 4px;
        transition: all 0.2s;

        &:hover {
          background-color: rgba(97, 179, 246, 0.1);
        }
      }
    }

    .meeting-info {
      margin: 0 0 auto;

      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        font-size: 13px;
        color: #606266;

        .info-icon {
          margin-right: 8px;
          color: #909399;
        }

        .info-text {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          &.location {
            font-weight: 500;
            color: #409eff;
          }
        }
      }
    }
  }
}

.config {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 12px;
  margin-top: auto;
  border-top: 1px solid #f0f0f0;

  .action-btn {
    display: flex;
    align-items: center;
    padding: 6px 8px;
    border-radius: 4px;
    transition: all 0.2s;

    &:hover {
      background-color: rgba(97, 179, 246, 0.1);
    }

    &.delete:hover {
      background-color: rgba(253, 80, 88, 0.1);
    }
  }
}

.text-base {
  margin-left: 4px;
  font-size: 12px;
  font-weight: 500;
}

// 二维码弹窗样式
.qrcode-dialog {
  :deep(.el-dialog__header) {
    padding-bottom: 10px;
    font-weight: bold;
    text-align: center;
  }
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 0;
}

.qrcode-title {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}

.qrcode-wrapper {
  padding: 10px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.qrcode-tips {
  margin-top: 15px;
  font-size: 14px;
  color: #606266;
}

.qrcode-actions {
  margin-top: 15px;
  text-align: center;
}
</style>
